/*
 * @Date: 2020-07-19 11:09:03
 * @LastEditors: liuzewen
 * @LastEditTime: 2020-10-31 18:41:12
 * @FilePath: \ESP32_UDP_test\src\main.cpp
 */
/*
 *  This sketch sends random data over UDP on a ESP32 device
 */

#include <WiFi.h>
#include <WiFiUdp.h>
#include <Arduino.h>
#include <MPU6050_tockn.h>
#include <Wire.h>
#include "bmp.h"

//长度为：(64*64)/8 = 512
#define bmp2_line 512

char greeting[bmp2_line*(4+4+2)] = "";

MPU6050 mpu6050(Wire);

long timer = 0;

const char * networkName = "liuzewen";
const char * networkPswd = "17609245102liu";
const char * ID = "手表2";

//UDP服务器和端口
const char * udpAddress = "255.255.255.255";
const int udpPort = 1234;

//Are we currently connected?
boolean connected = false;

//The udp library class
WiFiUDP udp;

//wifi event handler
void WiFiEvent(WiFiEvent_t event){
    switch(event) {
      case SYSTEM_EVENT_STA_GOT_IP:
          //When connected set 
          Serial.print("WiFi connected! IP address: ");
          Serial.println(WiFi.localIP());  
          //initializes the UDP state
          //This initializes the transfer buffer
          udp.begin(WiFi.localIP(),udpPort);
          connected = true;
          break;
      case SYSTEM_EVENT_STA_DISCONNECTED:
          Serial.println("WiFi lost connection");
          connected = false;
          break;
    }
}

void connectToWiFi(const char * ssid, const char * pwd){
  Serial.println("Connecting to WiFi network: " + String(ssid));

  // delete old config
  WiFi.disconnect(true);
  //register event handler
  WiFi.onEvent(WiFiEvent);
  
  //Initiate connection
  WiFi.begin(ssid, pwd);

  Serial.println("Waiting for WIFI connection...");
}

void setup(){
  Serial.begin(115200);

  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
  connectToWiFi(networkName, networkPswd);
/*
  sprintf(greeting,"\"%02X\"",bmp2[0]);
  for(int i = 1;i < bmp2_line;i++)
  {
    Serial.println(greeting);
    sprintf(greeting,"%s,\"%02X\"",greeting,bmp2[i]);
  }
  */
}

void loop(){
  mpu6050.update();

  if(millis() - timer > 100){
    if(connected){
      udp.beginPacket(udpAddress,udpPort);
      udp.printf("{\"ID\":\"%s\",\"angleX\":\"%.2f\",\"angleY\":\"%.2f\",\"angleZ\":\"%.2f\"}", ID,mpu6050.getAngleX(),mpu6050.getAngleY(),mpu6050.getAngleZ());
      udp.endPacket();
    }
    timer = millis();
  }
}

